/*
 * @Author: jhw
 * @Date: 2025-08-05 21:29:12
 * @LastEditors: jhw
 * @LastEditTime: 2025-08-15 13:13:52
 * @Description:
 */
import { defineStore } from 'pinia';
import {
  removeOptionsStatus,
  setOptionsStatus,
  setPositionStatus,
  setTextStatus,
  setSizeStatus,
  setPicLinkByIndex,
  setTypeStatus,
  setNoteDescTypeStatus,
  setOptionsStatusByIndex,
  setUse,
  setSwitchStatus,
} from './actions';
import type { Status, SurveyRes } from '@/types';
import { isNoteDesc } from '@/types';
import { initEditor } from '@/configs/initEditor';

export const useEditorStore = defineStore('editorStore', {
  state: () => ({
    // 渲染组件列表
    coms: initEditor(),
    // 当前组件索引
    currentComponentIndex: -1,
    // 问卷题目数量
    questionCount: 0,
  }),
  getters: {
    getSurveyTitle: (state) => {
      return state.coms[0].status.title.status;
    },
  },
  actions: {
    setTextStatus,
    setOptionsStatus,
    removeOptionsStatus,
    setPositionStatus,
    setSizeStatus,
    setPicLinkByIndex,
    setTypeStatus,
    setNoteDescTypeStatus,
    setUse,
    setOptionsStatusByIndex,
    setSwitchStatus,
    // 添加组件到coms
    addCom(com: Status) {
      this.coms.push(com);
      this.currentComponentIndex = -1; // 添加之后重置索引
      if (!isNoteDesc(com.name)) {
        this.questionCount++;
      }
    },
    // 在指定位置插入组件
    insertCom(com: Status, index: number) {
      this.coms.splice(index, 0, com);
      this.currentComponentIndex = -1; // 添加之后重置索引
      if (!isNoteDesc(com.name)) {
        this.questionCount++;
      }
    },
    // 删除组件
    removeCom(index: number) {
      // 先判断后删除，因为删除后索引会变化
      if (!isNoteDesc(this.coms[index].name)) {
        this.questionCount--;
      }
      this.coms.splice(index, 1);
      this.currentComponentIndex = -1;
    },
    // 设置当前组件索引
    setCurrentComponentIndex(index: number) {
      this.currentComponentIndex = index;
    },
    // 重置问卷
    resetComs() {
      this.coms = initEditor();
      this.currentComponentIndex = -1;
      this.questionCount = 0;
    },
    // 设置问卷
    setComs(coms: SurveyRes) {
      this.coms = coms.components;
      this.questionCount = coms.surveyCount;
      this.currentComponentIndex = -1;
    },
  },
});
